﻿import { AfterViewInit, Component, Injector, ViewEncapsulation, ViewChild } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { TenantDashboardServiceProxy, SalesSummaryDatePeriod, WorkBenchTechfileServiceProxy, TechFileOutServiceProxy } from '@shared/service-proxies/service-proxies';
import { curveBasis } from 'd3-shape'; 
import * as _ from 'lodash'; 
import { Table } from 'primeng/table';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import { Paginator, LazyLoadEvent } from 'primeng/primeng';

abstract class DashboardChartBase {
    loading = true;

    showLoading() {
        setTimeout(() => { this.loading = true; });
    }

    hideLoading() {
        setTimeout(() => { this.loading = false; });
    }
}

class SalesSummaryChart extends DashboardChartBase {
      
    data = [];

    constructor(
        private _WorkBenchService: WorkBenchTechfileServiceProxy) {
        super();
    } 
    init(salesSummaryData) { 
        this.setChartData(salesSummaryData);

        this.hideLoading();
    }

    setChartData(items): void {
        this.data = [];
        for (let i = 0; i < items.length; i++) {
            this.data.push({
                name: items[i].name,
                value: items[i].num
            });
        }
    }

    reload(datePeriod) { 

        this.showLoading();
      
            this._WorkBenchService
            .getTechFileCount(1)
            .subscribe(result => { 
                this.init(result.newNumberofTypes);
                this.hideLoading();
            });
    }
}

class RegionalStatsTable extends DashboardChartBase {
    stats: Array<any>; 
    curve: any = curveBasis;

    constructor(private _WorkBenchService: WorkBenchTechfileServiceProxy) {
        super();
    }

    init() {
        this.reload();
    } 
    reload() {
        this.showLoading();
        
            this._WorkBenchService
            .getBorrowDetailed(
                undefined,
                undefined,
                undefined,
                undefined,
                undefined,
                5,
                0
            )
            .subscribe(result => {
                this.stats=result.items;
                this.hideLoading();

            });
    }
}
 

class GeneralStatsPieChart extends DashboardChartBase {

    public data = [];
    public colorScheme = {
        domain: ['#5AA454', '#E44D25', '#CFC0BB', '#7aa3e5', '#a8385d', '#aae3f5']
      }; 
    constructor(private _WorkBenchService: WorkBenchTechfileServiceProxy ) {
        super();
    }

    init(redata) {

        this.data = [];
        for (let i = 0; i < redata.length; i++) {
            this.data.push({
                name: redata[i].name,
                value: redata[i].num
            });
        }



        // this.data = [
        //     {
        //         'name': 'Operations',
        //         'value': transactionPercent
        //     }, {
        //         'name': 'New Visits',
        //         'value': newVisitPercent
        //     }, {
        //         'name': 'Bounce',
        //         'value': bouncePercent
        //     }];

        this.hideLoading();
    }

    reload() {
        this.showLoading(); 
            this._WorkBenchService
            .getTechFileCount(1)
            .subscribe(result => {
                this.init(result.borrowNumberofTypes);
                this.hideLoading();
            });
    }
}

class DailySalesLineChart extends DashboardChartBase {
    

    chartData: any[];
    scheme: any = {
        name: 'green',
        selectable: true,
        group: 'Ordinal',
        domain: [
            '#34bfa3'
        ]
    };

    constructor(private _WorkBenchService: WorkBenchTechfileServiceProxy) {
        super();
    }

    init(data) {
        this.chartData = [];
        for (let i = 0; i < data.length; i++) {
            this.chartData.push({
                name: data[i].name,
                value: data[i].num
            });
        }
    }

    reload() {
        this.showLoading();
        
            this._WorkBenchService
            .getTechFileCount(1)
            .subscribe(result => { 
                this.init(result.newNumberofTypes); 
                this.hideLoading();
            });
    }
}

class ProfitSharePieChart extends DashboardChartBase { 
    chartData: any[] = [];
    scheme: any = {
        name: 'custom',
        selectable: true, 
        group: 'Ordinal',
        domain: [
            '#00c5dc', '#ffb822', '#716aca', '#00FF7F', '#F0E68C', '#FF7F50','#808080'
        ]
    };

    constructor(private _WorkBenchService: WorkBenchTechfileServiceProxy) {
        super();
    }

    init(data) {

        let formattedData = [];
        for (let i = 0; i < data.length; i++) {
            formattedData.push({
                'name': data[i].name,
                'value': data[i].num
            });
        }

        this.chartData = formattedData;
    }

    getChartItemName(index: number) {
        if (index === 0) {
            return 'Product Sales';
        }

        if (index === 1) {
            return 'Online Courses';
        }

        if (index === 2) {
            return 'Custom Development';
        }

        return 'Other';
    }
}

class DashboardHeaderStats extends DashboardChartBase {

    totalProfit = 0; totalProfitCounter = 0;
    voids = 0; voidsCounter = 0; 
    newUsers = 0; newUsersCounter = 0;

    totalProfitChange = 76; totalProfitChangeCounter = 0;
    voidsChange = 85; voidsChangeCounter = 0; 
    newUsersChange = 57; newUsersChangeCounter = 0;

    init(totalProfit,totalProfitChange,voids,voidsChange,newUsers, newUsersChange){
        this.totalProfit = totalProfit;
        this.totalProfitChange=totalProfitChange;
        this.voids = voids; 
        this.voidsChange=voidsChange;
        this.newUsers = newUsers;
        this.newUsersChange=newUsersChange;
        this.hideLoading();
    }
}
 
class MemberActivityTable extends DashboardChartBase {

    memberActivities: Array<any>;

    constructor(private _WorkBenchService: WorkBenchTechfileServiceProxy) {
        super();
    }

    init() {
        this.reload();
    }

    reload() {
        // this.showLoading();
        // this._dashboardService
        //     .getMemberActivity()
        //     .subscribe(result => {
        //         this.memberActivities = result.memberActivities;
        //         this.hideLoading();
        //     });
             
    }
}


@Component({
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.less'],
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class DashboardComponent extends AppComponentBase implements AfterViewInit {
    layer = 0;
    legendPosition: string = 'below';
    lave="总数";
    laveBorrow="借出";
    types="类型";
    stage=0;
    security=0;
    filetype=0;
    filterText = '';
    appSalesSummaryDateInterval = SalesSummaryDatePeriod;
    selectedSalesSummaryDatePeriod: any = SalesSummaryDatePeriod.Daily;
    dashboardHeaderStats: DashboardHeaderStats;
    salesSummaryChart: SalesSummaryChart;
    regionalStatsTable: RegionalStatsTable;
    generalStatsPieChart: GeneralStatsPieChart;
    dailySalesLineChart: DailySalesLineChart;
    profitSharePieChart: ProfitSharePieChart;
    memberActivityTable: MemberActivityTable;   
    @ViewChild('dataTableSpecialProductions') dataTableSpecialProductions: Table;
    @ViewChild('dataTableRecoverProductions') dataTableRecoverProductions: Table;
  
    @ViewChild('paginatorSpecial') paginatorSpecial: Paginator;
    @ViewChild('paginatorRecover') paginatorRecover: Paginator; 

    primengTableHelperSpecialProductions = new PrimengTableHelper();
    primengTableRecoverProductions = new PrimengTableHelper();

    constructor(
        injector: Injector,
        private _dashboardService: TenantDashboardServiceProxy,   //示例接口
        private _WorkBenchService: WorkBenchTechfileServiceProxy
    ) {
        super(injector);
        this.dashboardHeaderStats = new DashboardHeaderStats();
        this.salesSummaryChart = new SalesSummaryChart(this._WorkBenchService);
        this.regionalStatsTable = new RegionalStatsTable(this._WorkBenchService);
        this.generalStatsPieChart = new GeneralStatsPieChart(this._WorkBenchService);
        this.dailySalesLineChart = new DailySalesLineChart(this._WorkBenchService);
        this.profitSharePieChart = new ProfitSharePieChart(this._WorkBenchService);
        this.memberActivityTable = new MemberActivityTable(this._WorkBenchService);

        
    }

    getDashboardStatisticsData(datePeriod): void {
        this.salesSummaryChart.showLoading();
        this.generalStatsPieChart.showLoading();

        this._dashboardService
            .getDashboardData(datePeriod)
            .subscribe(result => {
                // this.dashboardHeaderStats.init(result.totalProfit, result.newFeedbacks, result.newOrders, result.newUsers);
                // this.generalStatsPieChart.init(result.transactionPercent, result.newVisitPercent, result.bouncePercent);
                //this.dailySalesLineChart.init(result.dailySales);
                // this.profitSharePieChart.init(result.profitShares);
                // this.salesSummaryChart.init(result.salesSummary, result.totalSales, result.revenue, result.expenses, result.growth);
                
            });
    }

    getTechfileDataOutput(): void {
        this.salesSummaryChart.showLoading();
        this.generalStatsPieChart.showLoading();
        
        if(this.isGranted('Pages.Tenant.Dashboard.Generallibrary'))
        { 
            this.layer =1;
        }
        else if(this.isGranted('Pages.Tenant.Dashboard.SubDatabase'))
        {
            this.layer =2;
        }
        else
        {
            this.layer =3;
        }
        this._WorkBenchService
            .getTechFileCount(this.layer)
            .subscribe(result => {
                this.dashboardHeaderStats.init(result.totalProfit, result.totalProfitChange, result.voids,result.voidsChange, result.newUsers, result.newUsersChange);
                this.dailySalesLineChart.init(result.numberofModels);
                 this.profitSharePieChart.init(result.numberofTypes);
                 this.generalStatsPieChart.init(result.borrowNumberofTypes);
                this.salesSummaryChart.init(result.newNumberofTypes);

            });
    }

    ngAfterViewInit(): void {
        this.getDashboardStatisticsData(SalesSummaryDatePeriod.Daily);
        this. getTechfileDataOutput();
        // this.regionalStatsTable.init();
        this.memberActivityTable.init();
        this.paginatorSpecial.changePage(this.paginatorSpecial.getPage());
        this.paginatorRecover.changePage(this.paginatorRecover.getPage());
    }


  
     
    
    getSpecialProduction(event?: LazyLoadEvent) { 
        if (this.primengTableHelperSpecialProductions.shouldResetPaging(event)) {
          this.paginatorSpecial.changePage(0);
    
          return;
        }
        this.primengTableHelperSpecialProductions.showLoadingIndicator();
    
        this._WorkBenchService.getBorrowDetailed(
          this.filetype==0?undefined:this.filetype,
          this.stage==0?undefined:this.stage,
          this.security==0?undefined:this.security,
          this.filterText,
          this.primengTableHelperSpecialProductions.getSorting(this.dataTableSpecialProductions),
          this.primengTableHelperSpecialProductions.getMaxResultCount(this.paginatorSpecial, event),
          this.primengTableHelperSpecialProductions.getSkipCount(this.paginatorSpecial, event)
        )
          .subscribe((result) => {
            this.primengTableHelperSpecialProductions.totalRecordsCount = result.totalCount;
            this.primengTableHelperSpecialProductions.records = result.items;
            this.primengTableHelperSpecialProductions.hideLoadingIndicator();
    
          });

           
        
          
      }
 getrecover(event?: LazyLoadEvent) { 
    if (this.primengTableRecoverProductions.shouldResetPaging(event)) {
      this.paginatorRecover.changePage(0);

      return;
    }
    this.primengTableRecoverProductions.showLoadingIndicator();

    this._WorkBenchService.getBorrowDetailed_GG(
      this.filetype==0?undefined:this.filetype,
      this.stage==0?undefined:this.stage,
      this.security==0?undefined:this.security,
      this.filterText,
      this.primengTableRecoverProductions.getSorting(this.dataTableRecoverProductions),
      this.primengTableRecoverProductions.getMaxResultCount(this.paginatorRecover, event),
      this.primengTableRecoverProductions.getSkipCount(this.paginatorRecover, event)
    )
      .subscribe((result) => {
        this.primengTableRecoverProductions.totalRecordsCount = result.totalCount;
        this.primengTableRecoverProductions.records = result.items;
        this.primengTableRecoverProductions.hideLoadingIndicator();

      });
  }
}
